package org.gnuklub;

import java.io.IOException;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ToneGenerator;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;

public class DTMF {
	private final Activity host;

	public DTMF(Activity host) {
		this.host = host;
	};

	public void playNumber(String number) {

		for (int i = 0; i < number.length(); i++) {

			Character digit = number.charAt(i);
			switch (digit) {
			case '0':
				playDigit(R.raw.tone_0);
				playDigit(R.raw.tone_silence);
				break;
			case '1':
				playDigit(R.raw.tone_1);
				playDigit(R.raw.tone_silence);
				break;
			case '2':
				playDigit(R.raw.tone_2);
				playDigit(R.raw.tone_silence);
				break;
			case '3':
				playDigit(R.raw.tone_3);
				playDigit(R.raw.tone_silence);
				break;
			case '4':
				playDigit(R.raw.tone_4);
				playDigit(R.raw.tone_silence);
				break;
			case '5':
				playDigit(R.raw.tone_5);
				playDigit(R.raw.tone_silence);
				break;
			case '6':
				playDigit(R.raw.tone_6);
				playDigit(R.raw.tone_silence);
				break;
			case '7':
				playDigit(R.raw.tone_7);
				playDigit(R.raw.tone_silence);
				break;
			case '8':
				playDigit(R.raw.tone_8);
				playDigit(R.raw.tone_silence);
				break;
			case '9':
				playDigit(R.raw.tone_9);
				playDigit(R.raw.tone_silence);
				break;
			}

		}
	}

	public void playDigit(int resid) {
		try {
			AssetFileDescriptor afd = host.getResources().openRawResourceFd(resid);
			Log.d("player",resid+"",null);
			if (afd != null) {
				MediaPlayer mp = new MediaPlayer();
				mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),	afd.getLength());
				afd.close();
				mp.prepare();

				mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mp.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.release();
					}
				});
				mp.start();
			}
		} catch (IOException ex) {
			Log.d("player", "create failed:", ex);
		} catch (IllegalArgumentException ex) {
			Log.d("player", "create failed:", ex);
		} catch (SecurityException ex) {
			Log.d("player", "create failed:", ex);
		}
	}

}
